
<?php

include "init.php";


switch ($_POST["type"]) {
  case 'show':
    show($db_conn);
    break;
  case "unclaimed"://未領取
    $sql = "SELECT `rp_id`, `rp_name`, `rp_create_datetime`, `rp_used_datetime` FROM `reward_pool` WHERE `rp_used_datetime` IS NULL";
    $result = mysqli_query($db_conn, $sql);
    echo json_encode(mysqli_fetch_all($result));
    break;
  case "roundShow":
    $sql = "SELECT * FROM `reward_pool` WHERE `rp_used_datetime` is null ORDER BY RAND() LIMIT 1 ";
    $result = mysqli_query($db_conn, $sql);
    $resultEcode = json_encode(mysqli_fetch_all($result));
    $row = mysqli_affected_rows($db_conn);

    if ((int) $row > 0) {
      $resultDcode = json_decode($resultEcode, true);
      $resultId = (int) $resultDcode[0][0];
      $now = date('Y-m-d H:i:s', time()); //定義當前時間  
     // $sqlUpdate = "UPDATE `reward_pool` SET `rp_used_datetime`='" . $now . "' WHERE `rp_id`='" . $resultId . "'";
    $sqlUpdate = strtr("UPDATE `reward_pool` SET `rp_used_datetime`='{$now}' WHERE `rp_id`='{$resultId}'",["{$now}"=>$now,"$resultId"=>$resultId]);

      mysqli_query($db_conn, $sqlUpdate);

      echo $resultEcode;
    } else {
      $error = array('error');
      echo json_encode($error);
    }
    break;
}
mysqli_close($db_conn);

function show($db_conn) {
  $sql = 'SELECT `rp_id`, `rp_name`, `rp_create_datetime`, `rp_used_datetime` FROM `reward_pool`';
  $result = mysqli_query($db_conn, $sql);
  echo json_encode(mysqli_fetch_all($result));
}
